
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: GAOBO
 * Date: 2020-02-20
 * Time: 16:31
 */

 class ReflectClassDemo {
    // 创建对象
    public static void reflectNewInstance()  {


        try {
            Class<?>  classStudent=Class.forName("Student");
            Object object = classStudent.newInstance();

            Student student=(Student) object;
            System.out.println("获取的学生对象"+student);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    // 反射私有的构造方法 屏蔽内容为获得公有的构造方法
    public static void reflectPrivateConstructor() {

        try {
            Class<?>  classStudent=Class.forName("Student");
            Constructor<?> declaredConstructor = classStudent.getDeclaredConstructor(String.class, int.class);
            declaredConstructor.setAccessible(true);
            Object object=declaredConstructor.newInstance("xiaobi",20);
            Student student=(Student) object;
            System.out.println(student);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
    // 反射私有属性
    public static void reflectPrivateField() {
        try {
            Class<?> classStudent = Class.forName("Student");
            Field age = classStudent.getDeclaredField("age");
            age.setAccessible(true);
//            Student student=(Student)classStudent.newInstance();
            Student student1=new Student();
            age.set(student1,302);

            Object o = age.get(student1);
            System.out.println(o.toString());

//            System.out.println(student1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    // 反射私有方法
    public static void reflectPrivateMethod() {
        try {
            Class<?> classStudent = Class.forName("Student");
            Method function = classStudent.getDeclaredMethod("function", String.class);
            System.out.println("获取的方法名"+function.getName());
            function.setAccessible(true);
            Object o = classStudent.newInstance();
            Student student=(Student)o;

            function.invoke(o,"哈哈哈可以自己传参了，私有方法");


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) {
//        reflectNewInstance();
//        reflectPrivateConstructor();
//        reflectPrivateField();
        reflectPrivateMethod();
    }
}